require 'active_unreal/document'

class Collection
  def initialize
    @documents = []
  end
  
  def insert(*documents)
    documents.each do |document|
      if document.is_a?(Document) and !get(document['document_id'])
        @documents << document
      end
    end
  end
  
  def remove(*document_ids)
    document_ids.each{|document_id| @documents.delete_if{|doc| doc['document_id'] == document_id}}
  end
  
  def update(document)
    if document.is_a?(Document) and get(document['document_id'])
      remove(document['document_id'])
      @documents << document
    else
      false
    end
  end
  
  def get(document_id)
    @documents.each do |doc|
      if doc['document_id'] == document_id
        return doc
      end
    end
    return nil
  end
  
  def each
    @documents.each{|doc| yield(doc)}
  end
  
  def filter(*args)
    @documents.each do |doc|
      result = []
      args.each{|arg| result << doc[arg]}
      i = 0
      str_res = "yield(" 
      result.length.times do |i|
        str_res += "result[" + i.to_s + "]"
        str_res += ", " if i != result.length
      end
      str_res += ")"
      eval(str_res)
    end
  end
end
